import { ref, reactive, createVNode } from "vue";
// 导入提示方法
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
// 导入回显用户数据和编辑用户接口
import { echoUser, editUser } from "@/api/userAPI";

export const useEditUser = (getUserData) => {
  // 编辑用户框显示状态
  const editVisible = ref(false);

  // 表单内容
  const editModel = reactive({
    username: "",
    password: "",
    email: "",
    mobile: "",
    role_id: "3",
    status: true,
  });

  // 存储用户id
  const userId = ref(null);

  // 点击编辑用户显示编辑用户框
  const handleShowEditModal = (id) => {
    userId.value = id;

    // 参数
    const query = {
      id,
    };
    // 发送请求获取回显数据
    echoUser(query)
      .then((res) => {
        if (res.status === 200) {
          const { username, email, mobile, role_id, status } = res.data[0];
          editModel.username = username;
          editModel.email = email;
          editModel.mobile = mobile;
          editModel.role_id = String(role_id);
          editModel.status = status == "true" ? true : false;
          editVisible.value = true;
        }
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  // 表单ref
  const editFormRef = ref(null);

  // 关闭模态框
  const editCloselModal = () => {
    editFormRef.value.resetFields();
  };

  // 点击确认
  const handleEditOk = () => {
    editFormRef.value
      .validate()
      .then((res) => {
        // 二次确认
        Modal.confirm({
          title: "确认提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "您是否确认编辑用户",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            const { username, password, email, mobile, role_id, status } = res;
            // 参数
            const params = {
              user_id: userId.value,
              username,
              password,
              email,
              mobile,
              role_id: parseInt(role_id),
              status: String(status),
            };
            // 发送请求编辑用户
            editUser(params)
              .then((res) => {
                if (res.status === 205) {
                  message.info(res.msg);
                }
                if (res.status === 200) {
                  message.success(res.msg);
                  editVisible.value = false;
                  // 重新获取数据渲染
                  getUserData();
                }
              })
              .catch((error) => {
                throw new Error(error);
              });
          },
          onCancel() {
            message.info("已取消");
          },
        });
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  return {
    editVisible,
    editModel,
    handleShowEditModal,
    editFormRef,
    editCloselModal,
    handleEditOk,
  };
};
